package service

import (
	"context"
	"mini-app/config/mysql"
	"mini-app/internal/dao"
	"mini-app/internal/models"
	"mini-app/internal/pkg"
	"time"

	"192.168.1.75/go-pkg/errorx"
)

type Announcement struct{}

func (Announcement) Create(
	ctx context.Context,
	record models.Announcement,
) (id string, err error) {
	if record.Content != "" {
		record.Content = pkg.RichTextConvert(record.Content)
	}
	return dao.Announcement{}.Create(ctx, mysql.NewDB(), record)
}
func (Announcement) Update(
	ctx context.Context,
	id, name, content string,
	startTime, endTime int64,
) error {
	if content != "" {
		content = pkg.RichTextConvert(content)
	}
	return dao.Announcement{}.Update(ctx, *mysql.NewDB(), id, name, content, startTime, endTime)
}
func (Announcement) Delete(
	ctx context.Context,
	id string,
) error {
	success := dao.Announcement{}.Delete(ctx, mysql.NewDB(), id)
	if !success {
		return errorx.New("删除失败", -1)
	}
	return nil
}
func (Announcement) List(
	ctx context.Context,
	name string,
	status int, // 1-进行中 2-未开始 3-已结束
	page, limit int,
) (list []models.Announcement, total int64) {
	nowTS := time.Now().Unix()
	records, total := dao.Announcement{}.List(ctx, mysql.NewDB(), name, status, page, limit)
	for index, record := range records {
		if nowTS >= record.StartTime && nowTS <= record.EndTime {
			records[index].Status = 2 // 进行中
		} else if nowTS < record.StartTime {
			records[index].Status = 1 // 未开始
		} else if nowTS > record.EndTime {
			records[index].Status = 3 // 已结束
		}
	}
	return records, total
}
